﻿using System;
using System.IO.Ports;
using System.NETool;
using Sunny.Com;

namespace Sunny.FrameDecoder.Demo
{
    public class Program
    {
        private static HeaderTagLengthValueTailFrameDecoder _decoder;
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            _decoder = new([0xFF, 0xFF], [0xF7, 0xF7], 2, LengthType.UShort);
            _decoder.OnDecoder += Decoder_OnDecoder;

            // 9600, N ,8 ,1
            ComPort com = new ComPort(ComDataType.HEX, "COM3", 9600, Parity.None, 8, StopBits.One);
            com.ReadTimeSpan = TimeSpan.FromMilliseconds(100);
            com.Received += Com_Received;
            bool isOpen = com.TryOpen();
            Console.Write(com.PortName);
            Console.WriteLine(isOpen ? " 串口打开成功" : " 串口打开失败");

            Console.ReadLine();

            TestByteFrameDecoder.TestFixedLengthFrameDecoder();
            TestByteFrameDecoder.TestDelimiterBasedFrameDecoder();
            TestByteFrameDecoder.TestHeaderDelimiterFrameDecoder();
            TestByteFrameDecoder.TestHeaderTailFrameDecoder();
            TestByteFrameDecoder.TestLengthValueFrameDecoder();
            TestByteFrameDecoder.TestTagLengthValueFrameDecoder();
            TestByteFrameDecoder.TestHeaderTagLengthValueTailFrameDecoder();

            TestStringFrameDecoder.TestNMEA0183FrameDecoder();
            TestStringFrameDecoder.TestLineBasedFrameDecoder();

            TestByteFrameDecoder.TestCreateFrame();
        }

        private static void Com_Received(ComPort sender, ComDataEventArgs e)
        {
            Console.WriteLine("串口接收: " + e.Buffer.ToHexString());
            _decoder.Decode(e.Buffer);
        }

        private static void Decoder_OnDecoder(object sender, ByteFrameEventArgs e)
        {
            Console.WriteLine("数据解码: " + e.Buffer.ToHexString());
        }
    }
}